// var Host = "http://192.168.11.63:7001/emsc-pub-api";
// var Host = "http://14.23.146.234:7000/emsc-pub-api";
 var Host = "https://emsc.cx580.com/emsc-pub-api";
//var Host = "http://emsc.cx580.com:8093/emsc-pub-api";

var Rule = {
    required: {key: "required", value: "不能为空!"}
};
var FootConvenientService = {
    appid: 'wxc1257fe34b8d3264',
    path: '',
    envVersion: 'release'
};
/** 返回是将pageObj的data赋值
 * address（选择后的文本地址xxx-xx-xx）
 * @param pageObj
 * @returns {Promise}
 */
function initAddress(pageObj) {
    pageObj.setData({
        isShow: false, // 显示区域选择框
        showDistrict: true // 默认为省市区三级区域选择
    });
    var opt1 = {
        url: Host+"/wx/c/p.ajax",
        data: {},
        showLoadFlag:"false",
        sucFn:function (province) {
            var firstProvince = province.body.result[3];

            pageObj.setData({//默认选择获取的省份第一个省份数据
                proviceData: province.body.result
            });

            var opt2 = {
                url: Host + "/wx/c/c1.ajax",
                data: {"provinceId": firstProvince.id},
                showLoadFlag:"false",
                sucFn: function (city) {
                    var firstCity = city.body.result[0];
                    pageObj.setData({
                        cityData: city.body.result
                    });
                    var opt3 = {
                        url: Host + "/wx/c/c2.ajax",
                        data: {"cityId": firstCity.id},
                        showLoadFlag:"false",
                        sucFn: function (district) {
                            pageObj.setData({
                                value: [3, 0, 0],//默认广东省
                                districtData: district.body.result
                            });
                        }
                    };
                    ajax(opt3);
                }
            };
            ajax(opt2);
        }
    };
    ajax(opt1)
}
function bindAddressChange(e,pageObj) {
    const current_value = e.detail.value, _data = pageObj.data;
    if (current_value.length > 2) {
        if (pageObj.data.value[0] !== current_value[0] ) {  // 滑动省份
            var opt1 = {
                url: Host + "/wx/c/c1.ajax",
                showLoadFlag:"false",
                data: {"provinceId": _data.proviceData[current_value[0]].id},
                sucFn: function (city) {
                    pageObj.setData({
                        value: [current_value[0], 0, 0],
                        cityData: city.body.result
                    });
                    var opt2 = {
                        url: Host + "/wx/c/c2.ajax",
                        showLoadFlag:"false",
                        data: {"cityId": city.body.result[0].id},
                        sucFn: function (district) {
                            if (district.body.result.length > 0) {
                                pageObj.setData({
                                    districtData: district.body.result
                                });
                            }
                        }
                    };
                    ajax(opt2);
                }
            };
            ajax(opt1);
        } else if (pageObj.data.value[0] === current_value[0] && pageObj.data.value[1] !== current_value[1] && pageObj.data.value[2] === current_value[2]) { // 滑动城市
            var opt = {
                url: Host + "/wx/c/c2.ajax",
                data: {"cityId": _data.cityData[current_value[1]].id},
                showLoadFlag:"false",
                sucFn: function (district) {
                    if (district.body.result.length > 0) {
                        pageObj.setData({
                            districtData: district.body.result,
                            value: [current_value[0], current_value[1], 0]
                        });
                    }
                }
            };
            ajax(opt);
        } else if (pageObj.data.value[0] === current_value[0] && pageObj.data.value[1] === current_value[1] && pageObj.data.value[2] !== current_value[2]) { // 滑动地区
            pageObj.setData({value: current_value});
        }
    }
}
function toast(msg,icon) {//只有成功和加载中提示
    var icon = (icon == null || icon == "" || typeof(icon) == "undefined") ? "success" : icon;
    wx.showToast({
        title: msg,
        icon: icon,
        duration: 2000
    });
}
function check(jsonArray,pageObj) {//自定义的校验接口
    var flag = true;
    for(var i=0;i<jsonArray.length;i++){
        var json = jsonArray[i];
        if(json.fn==null || json.fn=="" || typeof(json.fn)=="undefined"){
            if(json.rule.key==Rule.required.key
                &&json.value==''){
                errorToast(pageObj, json.message);
                pageObj.setData({
                    "errorFocusName":json.errorFocusName,
                    "errorScrollIntoViewName":json.errorScrollIntoViewName
                });
                flag = false;
                break;
            }
        }else{//自定义的验证函数
            if(!json.fn(json.value)){
                pageObj.setData({
                    "errorFocusName":json.errorFocusName,
                    "errorScrollIntoViewName":json.errorScrollIntoViewName
                });
                flag = false;
                break;
            }
        }
    }
    return flag;
}
function errorToast(pageObj,mes) {//显示错误提醒
    showPopErrorMes(pageObj,mes);
    hidePopErrorMes(pageObj);
}
function hidePopErrorMes(pageObj) {
    var fadeOutTimeout = setTimeout(() => {
            pageObj.setData({ popErrorMsg: '' });
    clearTimeout(fadeOutTimeout);
}, 3000);
}
function showPopErrorMes(pageObj,mes) {
    pageObj.setData(
        { popErrorMsg: mes}
    );
}
function ajaxError(pageObj, mes) {
    try{
        errorToast(pageObj, mes);
    }catch(e){
        console.log(mes);
    }

}
function ajax(opt) {
    opt.type = (opt.type==null || opt.type=="" || typeof(opt.type)=="undefined")? "POST" : opt.type;
    opt.data = (opt.data==null || opt.data=="" || typeof(opt.data)=="undefined")? {"date": new Date().getTime()} : opt.data;
    opt.sucFn = (opt.sucFn==null || opt.sucFn=="" || typeof(opt.sucFn)=="undefined")? {"date": new Date().getTime()} : opt.sucFn;
    opt.accountIdBlankFn = (opt.accountIdBlankFn==null || opt.accountIdBlankFn=="" || typeof(opt.accountIdBlankFn)=="undefined")? {"date": new Date().getTime()} : opt.accountIdBlankFn;
    opt.showLoadFlag = (opt.showLoadFlag==null || opt.showLoadFlag=="" || typeof(opt.showLoadFlag)=="undefined")? "true" : opt.showLoadFlag;

    if(opt.showLoadFlag=="true"){
        if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
            wx.showLoading({title: '加载中',mask:true});
        }else{
            wx.showToast({
                title: '加载中',
                icon: 'loading',
                duration:60000,
                mask:true
            });
        }
    }

    wx.request({
        url: opt.url,
        header: {'content-type': 'application/x-www-form-urlencoded'},
        data: opt.data,
        method: opt.type.toUpperCase(),
        success: function(res){
            if(opt.showLoadFlag=="true"){
                if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
                    wx.hideLoading();
                }else{
                    wx.hideToast();
                }
            }
            if(res.data.code==4444){//处理失败的结果
                if(res.data.msg.indexOf("accountId is blank.")>-1){
                    opt.accountIdBlankFn();
                }else{
                    ajaxError(opt.pageObj, res.data.msg);
                }
            }else{
                opt.sucFn(res.data);
            }

        },
        fail: function(){
            if(opt.showLoadFlag=="true"){
                if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
                    wx.hideLoading();
                }else{
                    wx.hideToast();
                }
            }
            if(opt.erFn==null || opt.erFn=="" || typeof(opt.erFn)=="undefined"){
                ajaxError(opt.pageObj, '网络错误，请退出再重新进入');
            }else{
                opt.erFn();
            }
        },
        complete:function (res) {
            if(opt.showLoadFlag=="true"){
                if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
                    setTimeout(function () {
                        wx.hideLoading();
                    },300)
                }else{
                    setTimeout(function () {
                        wx.hideToast();
                    },300)
                }
            }
            if(opt.completeFn!=null && opt.completeFn!="" && typeof(opt.completeFn)!="undefined"){
                if(res.data.code==4444){//处理失败的结果
                    ajaxError(opt.pageObj, res.data.msg);
                }else{
                    opt.completeFn(res.data);
                }
            }

        }
    })
}
function reLaunch(data) {
    if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
        wx.reLaunch({
            url: data.url
        })
    }else{
        wx.reLaunch({
            url: data.url
        })
    }
}
//时间戳转换时间
function toYMDDate(number){
    var n = number;
    var date = new Date(n);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
    return Y + M +  D;
}
//时间戳转换时间
function toYMDHMSDate(number){
    var n = number;
    var date = new Date(n);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return Y + M +  D+' '+h+':'+minute+':'+second;
}
//版本比较
function compareAppVersionToTarget  (curr, target) {//和目标的版本相比较，返回true表示大于或等于目标版本，否则就小于
    var separator = ".";
    if (curr == target) {
        return true;
    }

    var separator = separator || '.';
    var currArray = curr.split(separator);
    var targetArray = target.split(separator);
    var len = currArray.length;
    var left = 0;
    var right = 0;
    for (var i = 0; i < len; i++) {
        left = left + currArray[i];
        right = right + targetArray[i];
    }
    if (left >= right) {
        return true;
    } else {
        return false;
    }
}
//获取版本信息
function getSystemInfoSync() {
    var obj = wx.getStorageSync("VERSION");
    if(obj==null||obj==''){
        obj = wx.getSystemInfoSync();
        wx.setStorageSync("VERSION",obj);
    }
    return obj;
}
//微信支付
function requestPayment(opt) {
	wx.requestPayment({
		'timeStamp': opt.timeStamp,
		'nonceStr': opt.nonceStr,
		'package': opt.package,
		'signType':opt.signType,
		'paySign': opt.paySign,
		'success':function(res){
			if(opt.sucFn!=null&&opt.sucFn!="" &&typeof(opt.sucFn)!="undefined"){
				opt.sucFn(res);
			}
		},
		'fail':function(res){
			if(opt.failFn!=null&&opt.failFn!="" &&typeof(opt.failFn)!="undefined"){
				opt.failFn(res);
			}
		}
	})
}
module.exports = {
    Rule:Rule,
    Host:Host,
    FootConvenientService:FootConvenientService,
    toast:toast,
    reLaunch:reLaunch,
    errorToast:errorToast,
    hidePopErrorMes:hidePopErrorMes,
    check:check,
    initAddress:initAddress,
    bindAddressChange:bindAddressChange,
    ajax:ajax,
    toYMDDate:toYMDDate,
    toYMDHMSDate:toYMDHMSDate,
    requestPayment:requestPayment
};
